
// 队伍工具
export default class TeamUtils {

}

/**
 * 缓存组队邀请信息
 * @param {*} team_id 队伍id
 * @param {*} invite_id 邀请人id
 * @param {*} target_id 被邀请人id
 */
export function cache_team_invite(team_id, invite_id, target_id) {
    _TeamInvitDataCache.set(`${invite_id}_${target_id}`, {
        "team_id": team_id,
        "invite_id": invite_id,
        "target_id": target_id,
    });
}

/**
 * 获取组队邀请信息
 * @param {*} invite_id 邀请人id
 * @param {*} target_id 被邀请人id
 */
export function get_team_invite_cache(invite_id, target_id) {
    return _TeamInvitDataCache.get(`${invite_id}_${target_id}`);
}

/**
 * 删除组队邀请信息
 * @param {*} invite_id 邀请人id
 * @param {*} target_id 被邀请人id
 */
export function remove_team_invite_cache(invite_id, target_id) {
    return _TeamInvitDataCache.delete(`${invite_id}_${target_id}`);
}

/**
 * 获取队伍信息
 * @param {*} team_id 
 * @returns 
 */
export function get_team_data(team_id) {
    return _TeamDataCache.get(team_id);
}

/**
 * 删除队伍信息
 * @param {*} team_id 
 * @returns 
 */
export function remove_team_data(team_id) {
    return _TeamDataCache.get(team_id);
}


/**
 * 构建需要通知客户端的队伍信息
 * @param {*} team_id 
 * @returns 
 */
export function build_send_team_data(team_id) {
    let team_data = get_team_data(team_id);
    let send_team_data = {
        "阵型": team_data["阵型"],
        "限制等级": team_data["限制等级"],
        "成员": [],
    };
    team_member_callback(team_id, (index, characters_id, args) => {
        let characters = _CharactersData.get(characters_id);
        send_team_data["成员"].push(
            {
                "uid": characters["uid"],
                "模型": characters["模型"],
                "等级": characters["等级"],
                "名称": characters["名称"],
                "门派": characters["门派"],
                "染色方案": characters["染色方案"],
                "染色组": characters["染色组"],
                "炫彩": characters["炫彩"],
                "炫彩组": characters["炫彩组"],
                "当前称谓": characters["当前称谓"],
                "id": characters["id"],
                "变身数据": characters["变身数据"],
                "装备": characters["装备"][2],
                "锦衣": characters["锦衣"].map(e => { return e !== null ? e["名称"] : null }),
            }
        );
    });
    return send_team_data;
}

/**
 * 向队伍内所有人发送聊天框消息
 * @param {*} team_id 
 * @param {*} message 
 */
export function send_team_message(team_id, message) {
    let team_data = get_team_data(team_id);
    if (team_data !== "") {
        team_data["成员"].forEach(element => {
            let character_client_id = G.Characters.get_characters_client_id(element);
            if (character_client_id !== undefined) {
                G.ChatUtils.send_team_chat(character_client_id, message);
            }
        });
    }
}

/**
 * 向队伍内所有人发送聊天框消息
 * @param {*} team_id 
 * @param {*} message 
 */
export function send_team_url_message(team_id, message) {
    let team_data = get_team_data(team_id);
    if (team_data !== "") {
        team_data["成员"].forEach(element => {
            ClientUtils.send_characters_client_message(element, 113, message);
        });
    }
}


/**
 * 删除队伍数据
 * @param {*} team_id 
 */
export function remove_team(team_id) {
    let team_data = get_team_data(team_id);
    if (team_data !== undefined) {
        if (team_data["成员"] !== undefined) {
            send_team_message(team_id, "队伍已解散");
            team_data["成员"].forEach(characters_id => {
                let character = _CharactersData.get(characters_id);
                if (character !== undefined) {
                    let character_client_id = G.Characters.get_characters_client_id(characters_id);
                    if (character["队长"]) {
                        //通知关闭队伍图标
                        G.MapUtils.update_team_icon(characters_id, false);
                        //关闭队长开关
                        ClientUtils.send_client_message(character_client_id, 4008, 1);
                    }
                    character["队伍"] = 0;
                    character["队长"] = false;
                    if (character_client_id !== undefined) {
                        ClientUtils.send_basic_prompt(character_client_id, "队伍已解散");
                    }
                }

            });
        }
        remove_team_data(team_id);
        return true;
    }
    return false;
}

export function build_team_characters_data(characters) {
    return {
        "id": characters["id"],
        "名称": characters["名称"],
        "等级": characters["等级"],
        "门派": characters["门派"],
        "当前称谓": characters["当前称谓"],
        "模型": characters["模型"],
        "BPMC": characters["BPMC"],
    }
}

/**
 * 为角色创建一个队伍
 * @param {*} characters_id 
 */
export function create_team(characters_id) {
    let team_data = {
        "id": characters_id,
        "成员": [characters_id],
        "申请": [],
        "阵型": "普通",
        "限制等级": [1, 175],
    };
    _TeamDataCache.set(characters_id, team_data);

    let charactes = _CharactersData.get(characters_id);
    charactes["队伍"] = characters_id;
    charactes["队长"] = true;

    let send_data = build_send_team_data(characters_id);
    let character_client_id = G.Characters.get_characters_client_id(characters_id);
    if (character_client_id !== undefined) {
        //通知客户端更新组队信息
        ClientUtils.send_client_message(character_client_id, 4004, send_data);
        ClientUtils.send_client_message(character_client_id, 4006, 1);
        ClientUtils.send_basic_prompt(character_client_id, "组队成功,你现在是队长了。");
    }
    //通知客户端更新队标
    G.MapUtils.update_team_icon(characters_id, true);
}

/**
 * 添加助战到队伍
 * @param {*} characters 
 */
export function add_help_fight_to_team(client_id, characters) {
    let login_characters = G.Characters.get_current_login_characters(client_id);
    let team_data = get_team_data(login_characters["队伍"]);
    if (login_characters["队伍"] !== 0 && team_data === undefined) {
        //队伍数据没了
        if (!remove_team(login_characters["队伍"])) {
            login_characters["队伍"] = 0;
            login_characters["队长"] = false;
        }
    }
    if (login_characters["队伍"] === 0) {
        //主角色未组队 先创建一个队伍
        team_data = create_team(login_characters["id"]);
        login_characters["队伍"] = login_characters["id"];
        login_characters["队长"] = true;
    }
    if (!login_characters["队长"]) {
        ClientUtils.send_basic_prompt(client_id, "#Y/只有队长才以这种方式邀请小号进队！");
        return false;
    }
    if (team_data === undefined) {
        team_data = get_team_data(login_characters["队伍"]);
    }

    if (team_data["成员"].includes(characters["id"])) {
        ClientUtils.send_basic_prompt(client_id, "已在队伍中!");
        return false;
    }

    if (team_data["成员"].length >= 5) {
        ClientUtils.send_basic_prompt(client_id, "队伍人数已满！");
        return false;
    }

    team_data["成员"].push(characters["id"]);

    characters["队伍"] = login_characters["id"];
    characters["队长"] = false;

    // 剑会天下:同意入队(主号id,助战id) --剑会天下

    ClientUtils.send_basic_prompt(client_id, `#G${characters["名称"]}#Y加入了队伍`);
    send_team_message(team_data["id"], `#G${characters["名称"]}#Y加入了队伍`)
    let send_data = build_send_team_data(characters["队伍"]);
    team_data["成员"].forEach(e => {
        let character_client_id = G.Characters.get_characters_client_id(e);
        if (character_client_id !== undefined) {
            ClientUtils.send_client_message(character_client_id, 4004, send_data);
        }
    });
    // self:同步飞行坐骑(队伍id,id)
    return true;
}

/**
 * 添加指定角色到队伍中
 * @param {*} characters_id 
 */
export function add_characters_to_team(client_id, team_id, characters_id) {

    let characters = _CharactersData.get(characters_id);

    let team_data = get_team_data(team_id);

    if (team_data !== undefined) {
        if (team_data["成员"].length >= 5) {
            ClientUtils.send_basic_prompt(client_id, "队伍人数已满！");
            return false;
        }
        if (team_data["成员"].includes(characters["id"])) {
            ClientUtils.send_basic_prompt(client_id, "该成员已在队伍中!");
            return false;
        }
        characters["队伍"] = team_id;
        characters["队长"] = false;

        team_data["成员"].push(characters["id"]);

        let send_data = build_send_team_data(team_id);
        team_data["成员"].forEach(e => {
            let character_client_id = G.Characters.get_characters_client_id(e);
            if (character_client_id !== undefined) {
                ClientUtils.send_client_message(character_client_id, 4004, send_data);
                G.ChatUtils.send_team_chat(character_client_id, `#G${characters["名称"]}#Y加入了队伍`);
            }
        });
        let leader = _CharactersData.get(team_data["id"]);
        if (leader["地图数据"]["编号"] !== characters["地图数据"]["编号"]) {
            // 移动队员到队长地图
            G.MapUtils.move_characters_to_map(characters, leader["地图数据"]["编号"], leader["地图数据"]["x"], leader["地图数据"]["y"], false);
        }
        return true;

    }
    return false;
}

/**
 * 删除队伍中的指定角色
 * @param {*} characters_id 
 * @param {*} team_id 
 */
export function remove_team_characters(team_id, characters_id) {

    //离队的是队长,直接解散队伍
    if (team_id === characters_id) {
        remove_team(team_id);
        return true;
    }

    let characters = _CharactersData.get(characters_id);
    let team_data = get_team_data(team_id);

    let characters_index = undefined;
    team_data["成员"].forEach((value, index) => {
        if (value === characters_id) {
            characters_index = index;
        }
    });
    if (characters_index === undefined) {
        return false;
    }
    team_data["成员"].splice(characters_index, 1);

    let send_data = build_send_team_data(team_id);

    team_data["成员"].forEach(e => {
        let character_client_id = G.Characters.get_characters_client_id(e);
        if (character_client_id !== undefined) {
            ClientUtils.send_client_message(character_client_id, 4004, send_data);
            ClientUtils.send_basic_prompt(character_client_id, `#G${characters["名称"]}#Y离开队伍`);
            G.ChatUtils.send_team_chat(character_client_id, `#G${characters["名称"]}#Y离开队伍`);
        }
    });

    characters["队伍"] = 0;
    characters["队长"] = false;
    return true;
}

/**
 * 获取队员的下标
 * @param {*} characters_id 
 */
export function get_team_member_index(team_id, characters_id) {
    return team_member_callback(team_id, (index, characters_id, args) => {
        if (characters_id === args[0]) {
            return index;
        }
    }, characters_id);
}

/**
 * 获取队员信息 
 * @param {*} index 
 */
export function get_team_member(team_id, index) {
    let team_data = get_team_data(team_id);
    return _CharactersData.get(team_data["成员"][index]);
}

/**
 * 更换队长
 * @param {*} team_id 
 * @param {*} index 
 */
export function update_team_leader(team_id, index) {
    let team_data = get_team_data(team_id);
    if (team_data === undefined) {
        return 0;
    }
    let target = team_data["成员"][index];
    if (target === undefined) {
        return 0;
    }
    let new_leader_characters = _CharactersData.get(target);
    let new_leader_characters_client = G.Characters.get_characters_client_id(new_leader_characters["id"]);
    if (new_leader_characters_client === undefined) {
        return 0;
    }
    let old_leader_characters = _CharactersData.get(team_id);

    //更新队伍信息
    team_data["id"] = new_leader_characters["id"];
    team_data["成员"][0] = new_leader_characters["id"];
    team_data["成员"][index] = old_leader_characters["id"];
    _TeamDataCache.delete(team_id);
    _TeamDataCache.set(new_leader_characters["id"], team_data);

    //更新原队长和新队长的数据 通知关闭和开启队长权限
    let old_leader_characters_client = G.Characters.get_characters_client_id(old_leader_characters["id"]);
    old_leader_characters["队长"] = false;
    old_leader_characters["队伍"] = new_leader_characters["id"];
    ClientUtils.send_client_message(old_leader_characters_client, 4008, 1);
    G.MapUtils.update_team_icon(old_leader_characters["id"], false);
    new_leader_characters["队长"] = true;
    new_leader_characters["队伍"] = new_leader_characters["id"];
    //通知客户端自己是队长
    ClientUtils.send_client_message(new_leader_characters_client, 4006);
    G.MapUtils.update_team_icon(target, true);

    //通知所有队员更新信息
    let send_data = build_send_team_data(target);
    team_data["成员"].forEach(e => {
        if (e !== old_leader_characters_client["id"] && e !== new_leader_characters["id"]) {
            //更新队员的队伍id
            _CharactersData.get(e)["队伍"] = new_leader_characters["id"];
        }
        let character_client_id = G.Characters.get_characters_client_id(e);
        if (character_client_id !== undefined) {
            ClientUtils.send_client_message(character_client_id, 4004, send_data);
            ClientUtils.send_basic_prompt(character_client_id, `#G${new_leader_characters["名称"]}#Y提升为新队长`);
            G.ChatUtils.send_team_chat(character_client_id, `#G${new_leader_characters["名称"]}#Y提升为新队长`);
        }
    });
    return 1;
}

/**
 * 切换助战队长
 */
export function update_help_fight_leader(client_id, master_characters, characters) {
    let team_data = get_team_data(master_characters["id"]);
    if (team_data === undefined) {
        return;
    }
    let index = get_team_member_index(master_characters["id"], characters["id"]);

    //更新队伍信息
    team_data["id"] = characters["id"];
    team_data["成员"][0] = characters["id"];
    team_data["成员"][index] = master_characters["id"];
    _TeamDataCache.delete(master_characters["id"]);
    _TeamDataCache.set(characters["id"], team_data);

    //更新原队长和新队长的数据 通知关闭和开启队长权限
    master_characters["队长"] = false;
    master_characters["队伍"] = characters["id"];
    G.MapUtils.update_team_icon(master_characters["id"], false);

    characters["队长"] = true;
    characters["队伍"] = characters["id"];
    //通知客户端自己是队长
    ClientUtils.send_client_message(client_id, 4006);
    G.MapUtils.update_team_icon(characters["id"], true);

    //通知所有队员更新信息
    let send_data = build_send_team_data(characters["id"]);
    team_data["成员"].forEach(e => {
        if (e !== master_characters["id"] && e !== characters["id"]) {
            //更新队员的队伍id
            _CharactersData.get(e)["队伍"] = characters["id"];
        }
        let character_client_id = G.Characters.get_characters_client_id(e);
        if (character_client_id !== undefined) {
            ClientUtils.send_client_message(character_client_id, 4004, send_data);
            ClientUtils.send_basic_prompt(character_client_id, `#G${characters["名称"]}#Y提升为新队长`);
            G.ChatUtils.send_team_chat(character_client_id, `#G${characters["名称"]}#Y提升为新队长`);
        }
    });
    //通知客户端更新队伍信息
    ClientUtils.send_client_message(client_id, 4004, build_send_team_data(characters["队伍"]));
}

/**
 * 获取队伍平均等级
 */
export function get_team_avg_level(team_id) {
    let team_data = get_team_data(team_id);
    let level_sum = 0;
    team_data["成员"].forEach(characters_id => {
        let characters = _CharactersData.get(characters_id);
        level_sum = level_sum + characters["等级"]
    });
    return Math.floor(level_sum / team_data["成员"].length)
}

/**
 * 同步所有队员的剧情
 * @param {*} team_id 
 * @param {*} plot 
 */
export function sync_team_plot(team_id, plot) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        let characters = _CharactersData.get(team_characters_id);
        characters["剧情"] = plot;
        ClientUtils.send_characters_client_message(team_characters_id, 227, characters["剧情"]);
    });
}

/**
 * 为队伍成员添加剧情点
 * @param {*} team_id 
 * @param {*} num 
 */
export function add_plot_point(team_id, num) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        G.Characters.add_plot_point(team_characters_id, num)
    });
}

/**
 * 为队伍成员添加经验
 * @param {*} team_id 
 * @param {*} exp 
 */
export function add_exp(team_id, exp) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        G.Characters.add_exp(team_characters_id, exp);
    });
}

/**
 * 为队伍成员添加指定字段数值
 * @param {*} team_id 
 * @param {*} key 
 * @param {*} num 
 */
export function add_number_field_value(team_id, key, num) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        G.Characters.add_number_field_value(team_characters_id, key, num);
    });
}

/**
 * 为队伍成员添加物品
 * @param {*} team_id 
 * @param {*} item_name 
 * @param {*} num 
 */
export function add_item(team_id, item_name, num) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        G.Characters.add_item(team_characters_id, args[0], args[1]);
    }, item_name, num);
}

/**
 * 向队伍内所有玩家发送队伍聊天消息
 * @param {*} team_id 
 * @param {*} characters 
 * @param {*} text 
 */
export function send_team_characters_chat(team_id, characters, text) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        let character_client_id = G.Characters.get_characters_client_id(team_characters_id);
        if (character_client_id !== undefined) {
            G.ChatUtils.send_chat(character_client_id, args[0], args[1], G.ChatUtils.chat_type_enum.队伍[1]);
        }
    }, characters, text);
}

/**
 * 向队伍内所有玩家发送队伍聊天超链接消息
 * @param {*} team_id 
 * @param {*} characters 
 * @param {*} text 
 */
export function send_team_characters_url_chat(team_id, characters, text, url_data) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        let character_client_id = G.Characters.get_characters_client_id(team_characters_id);
        if (character_client_id !== undefined) {
            G.ChatUtils.send_url_chat(character_client_id, args[0], args[1], args[2], G.ChatUtils.chat_type_enum.队伍[1]);
        }
    }, characters, text, url_data);
}

/**
 * 同步队伍成员的飞行状态
 * @param {*} team_id 
 */
export function sync_team_flight(team_id) {
    let leader_characters = _CharactersData.get(team_id);
    let flight_status = leader_characters["飞行中"]
    if (flight_status) {
        let res = G.Characters.check_flight(leader_characters);
        if (!res[0]) {
            ClientUtils.send_characters_basic_prompt(team_id, res[1]);
            return;
        }
    }
    let code = flight_status ? 71 : 72;
    // if(leader_characters["飞行中"]){
    //     // TODO 如果检测到队友没有飞行坐骑的时候,且队伍在飞行中,应该取消飞行状态
    // }
    team_member_callback(team_id, (index, team_characters_id, args) => {
        let team_characters = _CharactersData.get(team_characters_id);
        team_characters["飞行中"] = args[0];
        ClientUtils.send_characters_client_message(team_characters_id, args[1]);
        G.MapUtils.update_characters_flight(team_characters_id);
    }, flight_status, code);
}

/**
 * 队伍平均等级
 * @param {*} team_id 
 * @returns 
 */
export function get_avg_level(team_id) {
    let team_data = get_team_data(team_id);
    let level_sum = 0;
    if (team_data !== undefined) {
        for (let index = 0; index < team_data["成员"].length; index++) {
            let team_characters_id = team_data["成员"][index];
            let team_characters = _CharactersData.get(team_characters_id);
            level_sum += team_characters["等级"];
        }
        return Math.floor(level_sum / team_data["成员"].length);
    }
    return _CharactersData.get(team_id)["等级"];
}

/**
 * 校验每个队伍成员的等级是否大于等于要求的等级
 * @param {*} team_id 
 * @param {*} level 
 * @returns 
 */
export function check_all_member_level(team_id, level) {
    let team_data = get_team_data(team_id);
    if (team_data) {
        for (let index = 0; index < team_data["成员"].length; index++) {
            let team_characters_id = team_data["成员"][index];
            let team_characters = _CharactersData.get(team_characters_id);
            if (team_characters === undefined || team_characters["等级"] < level) {
                return false;
            }
        }
        return true;
    }
    return false;
}

/**
 * 校验每个队伍成员是否完成了指定副本
 * @param {*} team_id 
 * @param {*} dungeon_id 
 * @returns 
 */
export function check_all_member_dungeon_success(team_id, dungeon_id) {
    return team_member_callback(team_id, (index, team_characters_id, args) => {
        if (_CharactersDungeonData.has(team_characters_id) &&
            _CharactersDungeonData.get(team_characters_id)[args[0]] &&
            _CharactersDungeonData.get(team_characters_id)[args[0]]["完成"]) {
            let team_characters = _CharactersData.get(team_characters_id);
            return team_characters["名称"];
        }
    }, dungeon_id);
}

/**
 * 校验每个队伍成员的副本是否超时
 * @param {*} team_id 
 * @param {*} dungeon_id 
 * @returns 
 */
export function check_all_member_dungeon_timout(team_id, dungeon_id) {
    return team_member_callback(team_id, (index, team_characters_id, args) => {
        if (_CharactersDungeonData.has(team_characters_id) &&
            _CharactersDungeonData.get(team_characters_id)[args[0]] &&
            _CharactersDungeonData.get(team_characters_id)[args[0]]["超时"] &&
            (_CharactersDungeonData.get(team_characters_id)[args[0]]["超时"] - Math.floor(Date.now() / 1000) > 1)
        ) {
            let team_characters = _CharactersData.get(team_characters_id);
            let second = _CharactersDungeonData.get(team_characters_id)[args[0]]["超时"] - Math.floor(Date.now() / 1000)
            return [team_characters["名称"], second];
        }
    }, dungeon_id);
}

/**
 * 校验每个队伍成员是否接取了指定任务
 * @param {*} team_id 
 * @param {*} task_number 
 * @returns 
 */
export function check_all_member_task(team_id, task_number) {
    return team_member_callback(team_id, (index, characters_id, args) => {
        if (G.CharactersTask.get_task_by_number(characters_id, args[0])) {
            let team_characters = _CharactersData.get(characters_id);
            return team_characters["名称"];
        }
    }, task_number);
}

/**
 * 为所有队员添加副本任务
 * @param {*} team_id 
 * @param {*} task_number 
 * @param {*} task_data 
 * @param {*} prompt_text 
 */
export function add_dungeon_task(team_id, task_number, task_data, prompt_text) {
    team_member_callback(team_id, (index, team_characters_id, args) => {
        // 初始化副本数据
        if (!_CharactersDungeonData.has(team_characters_id)) {
            _CharactersDungeonData.set(team_characters_id, {});
        }
        let dungeon_data = _CharactersDungeonData.get(team_characters_id);
        dungeon_data[task_number] = {
            "完成": false,
            "数量": 0,
            "进程": 1,
        };
        task_data["characters_id"] = team_characters_id;
        G.CharactersTask.add_task(team_characters_id, args[0], args[1]);
        ClientUtils.send_characters_basic_prompt(team_characters_id, args[2]);
    }, task_number, task_data, prompt_text);
}

/**
 * 队伍成员回调函数
 * @param {*} team_id 队伍id
 * @param {*} callback_fn 回调函数
 * @param  {...any} args 额外参数(回调函数内是数组)
 * @returns 
 */
export function team_member_callback(team_id, callback_fn, ...args) {
    let team_data = get_team_data(team_id);
    if (team_data !== undefined) {
        for (let index = 0; index < team_data["成员"].length; index++) {
            let characters_id = team_data["成员"][index];
            let res = callback_fn(index, characters_id, args);
            if (res) {
                return res;
            }
        }
    }
}
